<template>
  <div class="quill-editor-container">
    <quill-editor
      v-model:content="content"
      :options="editorOptions"
      content-type="html"
      @ready="onEditorReady"
      @change="onEditorChange"
    />
    <!-- 图片放大模态框 -->
    <div v-if="showImageModal" class="image-modal" @click="closeImageModal">
      <img :src="currentImageSrc" alt="放大图片" />
    </div>
  </div>
</template>

<script setup>
import 'quill/dist/quill.snow.css';

import { QuillEditor } from '@vueup/vue-quill';
import Quill from 'quill';
import { reactive, ref, watch } from 'vue';

// 获取用户store和token
const userStore = useUserStore();

// 注册字体和字号白名单
//  字体扩展
const Font = Quill.import('attributors/class/font');
Font.whitelist = ['songti', 'heiti', 'kaiti', 'yahei', 'PingFang '];
Quill.register(Font, true);

// 增加字体大小配置项
const FontAttributor = Quill.import('attributors/class/size');
FontAttributor.whitelist = ['ft10', 'ft12', 'ft14', 'ft16', 'ft18', 'ft32'];
Quill.register(FontAttributor, true);

// 使用 Quill.import 获取 Size
const Size = Quill.import('formats/size');
Quill.register(Size, true);

import { useUserStore } from '@/store';

// 定义事件
const emit = defineEmits(['update:modelValue', 'change']);

// 定义属性
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  height: {
    type: [String, Number],
    default: 400,
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
  readonly: {
    type: Boolean,
    default: false,
  },
});

// 编辑器内容
const content = ref(props.modelValue || '');
const quillInstance = ref(null);

// 监听内容变化，向父组件更新值
watch(content, (newVal) => {
  emit('update:modelValue', newVal);
});

// 监听父组件传入的值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== content.value) {
      content.value = newVal;
    }
  },
  { immediate: true },
);

// 检查用户权限
const checkUserPermission = () => {
  if (!userStore.token) {
    alert('请先登录后再使用编辑器功能');
    return false;
  }
  return true;
};

// 图片上传处理（添加token验证）
const handleImageUpload = () => {
  // 检查用户权限
  if (!checkUserPermission()) {
    return;
  }

  const input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/*');
  input.click();

  input.onchange = async () => {
    const file = input.files[0];
    if (!file) return;

    // 检查图片大小（限制5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB');
      return;
    }

    try {
      // 使用带token的图片上传接口
      const imageUrl = await uploadImageWithToken(file);
      const range = quillInstance.value.getSelection(true);
      quillInstance.value.insertEmbed(range.index, 'image', imageUrl);
    } catch (error) {
      console.error('图片上传失败:', error);
      alert(`图片上传失败: ${error.message || '未知错误'}`);
    }
  };
};

// 带token的图片上传函数
const uploadImageWithToken = (file) => {
  return new Promise((resolve, reject) => {
    // 检查token是否存在
    if (!userStore.token) {
      reject(new Error('用户未登录，无法上传图片'));
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    // 使用实际的上传接口
    fetch(`${import.meta.env.VITE_API_URL_PREFIX}/common/upload`, {
      method: 'POST',
      body: formData,
      headers: {
        Authorization: `Bearer ${userStore.token}`,
        // 注意：不要手动设置 Content-Type，让浏览器自动设置 multipart/form-data
      },
    })
      .then(async (response) => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        if (data.code === 200) {
          // 返回完整的图片URL
          const imageUrl = import.meta.env.VITE_PROXY_API_URL + data.fileName;
          resolve(imageUrl);
        } else {
          reject(new Error(data.msg || '上传失败'));
        }
      })
      .catch((error) => {
        console.error('Upload error:', error);
        reject(error);
      });
  });
};

// 编辑器配置
const editorOptions = reactive({
  theme: 'snow',
  modules: {
    toolbar: {
      container: [
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [
          { font: ['songti', 'heiti', 'kaiti', 'yahei', 'PingFang'] },
          { size: ['ft10', 'ft12', 'ft14', 'ft16', 'ft18', 'ft32'] },
        ],
        ['bold', 'italic', 'underline', 'strike'],
        [{ color: [] }, { background: [] }],
        ['link', 'image', 'video'],
        ['clean'],
      ],
      handlers: {
        image: handleImageUpload,
      },
    },
  },
});

// 编辑器准备就绪
const onEditorReady = (editor) => {
  console.log('Quill编辑器已初始化:', editor);
  quillInstance.value = editor;

  // 检查用户权限
  if (!checkUserPermission()) {
    // 如果用户未登录，设置为只读模式
    editor.disable();
    console.warn('用户未登录，编辑器已设置为只读模式');
  }

  // 设置编辑器高度
  const editorElement = editor.root.parentElement;
  if (editorElement) {
    editorElement.style.height = typeof props.height === 'number' ? `${props.height}px` : props.height;
  }
};

// 内容变化事件
const onEditorChange = (event) => {
  // 检查用户权限
  if (!checkUserPermission()) {
    return;
  }
  emit('change', event);
};

// 监听用户登录状态变化
watch(
  () => userStore.token,
  (newToken) => {
    if (quillInstance.value) {
      if (newToken) {
        // 用户已登录，启用编辑器
        quillInstance.value.enable();
        console.log('用户已登录，编辑器已启用');
      } else {
        // 用户已登出，禁用编辑器
        quillInstance.value.disable();
        console.log('用户已登出，编辑器已禁用');
      }
    }
  },
);

// 暴露方法给父组件
defineExpose({
  getEditor: () => quillInstance.value,
  getContent: () => content.value,
  setContent: (html) => {
    if (!checkUserPermission()) {
      console.warn('用户未登录，无法设置内容');
      return;
    }
    content.value = html;
  },
  insertText: (text) => {
    if (!checkUserPermission()) {
      console.warn('用户未登录，无法插入文本');
      return;
    }
    if (quillInstance.value) {
      const range = quillInstance.value.getSelection(true);
      quillInstance.value.insertText(range.index, text);
    }
  },
  focus: () => {
    if (quillInstance.value) {
      quillInstance.value.focus();
    }
  },
  // 新增方法：检查用户权限
  checkPermission: checkUserPermission,
});

// 图片放大相关状态
const showImageModal = ref(false);
const currentImageSrc = ref('');

// 打开图片模态框
const openImageModal = (src) => {
  currentImageSrc.value = src;
  showImageModal.value = true;
};

// 关闭图片模态框
const closeImageModal = () => {
  showImageModal.value = false;
};

// 添加图片点击事件监听
const addImageClickListener = () => {
  const editorElement = quillInstance.value?.root;
  if (editorElement) {
    editorElement.addEventListener('click', (event) => {
      const { target } = event;
      if (target.tagName === 'IMG') {
        openImageModal(target.src);
      }
    });
  }
};

// 在编辑器准备就绪时添加监听
watch(quillInstance, (instance) => {
  if (instance) {
    addImageClickListener();
  }
});
</script>

<style>
.quill-editor-container {
  width: 93%;
  position: relative;
}

/* 添加未登录状态的样式 */
.quill-editor-container.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.quill-editor-container.disabled::after {
  content: '请登录后使用编辑器功能';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 1000;
}

/* 字体样式映射 */
.ql-font-microsoft-yahei {
  font-family: 'Microsoft YaHei', sans-serif;
}
.ql-font-pingfang-sc {
  font-family: 'PingFang SC', sans-serif;
}
.ql-font-simsun {
  font-family: 'SimSun', serif;
}
.ql-font-fangsong {
  font-family: 'FangSong', serif;
}
.ql-font-simhei {
  font-family: 'SimHei', sans-serif;
}
.ql-font-kaiti {
  font-family: 'KaiTi', serif;
}
.ql-font-arial {
  font-family: Arial, sans-serif;
}
.ql-font-arial-black {
  font-family: 'Arial Black', sans-serif;
}
.ql-font-times-new-roman {
  font-family: 'Times New Roman', serif;
}
.ql-font-courier-new {
  font-family: 'Courier New', monospace;
}

/* 字体下拉菜单显示中文名 */
/* 字体样式 */
/* 字体样式 */
.ql-font-songti {
  font-family: 'SimSun', serif;
}
.ql-font-heiti {
  font-family: 'SimHei', sans-serif;
}
.ql-font-kaiti {
  font-family: 'KaiTi', serif;
}
.ql-font-yahei {
  font-family: 'Microsoft YaHei', sans-serif;
}
.ql-font-PingFang {
  font-family: 'PingFang SC', 'PingFang-sc', sans-serif;
}
.ql-font-fangsong {
  font-family: 'FangSong', serif;
}

/* 显示中文字体名称 */
.ql-picker.ql-font .ql-picker-label[data-value='songti']::before,
.ql-picker.ql-font .ql-picker-item[data-value='songti']::before {
  content: '宋体';
}
.ql-picker.ql-font .ql-picker-label[data-value='heiti']::before,
.ql-picker.ql-font .ql-picker-item[data-value='heiti']::before {
  content: '黑体';
}
.ql-picker.ql-font .ql-picker-label[data-value='kaiti']::before,
.ql-picker.ql-font .ql-picker-item[data-value='kaiti']::before {
  content: '楷体';
}
.ql-picker.ql-font .ql-picker-label[data-value='yahei']::before,
.ql-picker.ql-font .ql-picker-item[data-value='yahei']::before {
  content: '微软雅黑';
}
.ql-picker.ql-font .ql-picker-label[data-value='PingFang']::before,
.ql-picker.ql-font .ql-picker-item[data-value='PingFang']::before {
  content: '苹方';
}
.ql-picker.ql-font .ql-picker-label[data-value='fangsong']::before,
.ql-picker.ql-font .ql-picker-item[data-value='fangsong']::before {
  content: '仿宋';
}
/* 字号下拉菜单样式 */

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft10']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft10']::before {
  content: '10px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft12']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft12']::before {
  content: '12px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft14']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft14']::before {
  content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft16']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft16']::before {
  content: '16px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft18']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft18']::before {
  content: '18px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='ft32']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='ft32']::before {
  content: '32px';
}
.ql-size-ft10 {
  font-size: 10px;
}
.ql-size-ft12 {
  font-size: 10px;
}

.ql-size-ft14 {
  font-size: 14px;
}

.ql-size-ft16 {
  font-size: 16px;
}

.ql-size-ft18 {
  font-size: 18px;
}

.ql-size-ft32 {
  font-size: 32px;
}

/* 标题下拉菜单显示为 H1-H6 */
.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: '正文';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
  content: 'H1';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
  content: 'H2';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
  content: 'H3';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
  content: 'H4';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
  content: 'H5';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
  content: 'H6';
}

/* 限制图片最大宽度 */
.ql-editor img {
  max-width: 300px;
  width: 120px;
  height: auto;
  display: flex;
  margin: 10px auto;
  margin-left: 5px;
  cursor: pointer; /* 鼠标悬停在图片上时变成小手 */
}

/* 编辑器样式优化 */
.ql-editor {
  font-size: 16px; /* 强制固定字号 */
}

.ql-toolbar {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: none;
}

.ql-container {
  border-bottom: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-top: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ql-toolbar {
    flex-wrap: wrap;
  }

  .ql-editor {
    font-size: 16px !important; /* 强制固定字号 */
  }
}

.ql-editor .ql-size-small {
  font-size: 16px !important;
}

.ql-editor .ql-size-large {
  font-size: 16px !important;
}

.ql-editor .ql-size-huge {
  font-size: 16px !important;
}

/* 图片模态框样式 */
.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.image-modal img {
  max-width: 90%;
  max-height: 90%;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
